import React, { useEffect, useMemo, useRef, useState } from 'react';
import { env } from '@/utils/data';
import { getListApi } from '@/request/mind';

const UsedEnv = () => {
  const [useEnv, setUseEnv] = useState([]);
  const maxCount = useRef(0);
  const getUseEnv = async () => {
    try {
      const res: any = await getListApi();
      if (res) {
        setUseEnv(res);
      }
    } catch (err) {
      console.log(err);
    }
  };
  const envs = useMemo(() => {
    if (!useEnv) return {};
    const obj: any = {};
    // 生成环境对象
    const defineEnv: string[] = env.map((item) => item.value);
    defineEnv.forEach((item) => {
      obj[item] = 0;
    });
    for (let i = 0; i < useEnv.length; i += 1) {
      const { env: e } = useEnv[i];
      if (e) {
        obj[e] += 1;
      }
    }
    maxCount.current = Math.max.apply(null, Object.values(obj));
    return obj;
  }, [useEnv]);
  useEffect(() => {
    getUseEnv();
  }, []);
  return (
    <div className="used-env">
      {Object.keys(envs).map((item) => (
        <div key={item} className="env-box">
          <div className="env-item">
            <span>{item} </span>
            <span>({envs[item]})</span>
          </div>
          <div className="shape" style={{ width: `${((envs[item] * 60) / maxCount.current + 1.5).toFixed(2)}%` }}></div>
        </div>
      ))}
    </div>
  );
};

export default UsedEnv;
